<pre><?php

require('globals.php');
require('logger.php');

$handle = fopen($_FILES["importfile"]["tmp_name"], "r");

if (!$handle)
	die("File " . $_FILES["importfile"]["tmp_name"] . "does not exist or cannot be opened.");

$import = array();
$date = date('m.d.Y');
$j = 0;

$insert_statement_starter = "INSERT INTO " . $dealers_table .
	"(order_id,payment_amount,dealer_email,dealer_phone,dealer_address,
      dealer_city,dealer_post_code,dealer_country,payment_method,dealer_state,dealer_last_name,
      dealer_first_name,dealer_badge_number,dealership_name,tax_id,table_size_req,power,wall,
      table_adjacent_to,table_away_from,table_pref,requests,is_notified,notification_date,
      cancelled,cancelled_date,trouble,table_note,date_entered) VALUES (";

// connect to the mysql database server.
$connect = mysql_connect($host, $user, $password);
if (!$connect)
	die('Could not connect: ' . mysql_error());
mysql_select_db($database);

if ($handle) {
	while (($buffer = fgetcsv($handle,0,"\t")) !== false) {
		for ($i=0;$i<count($buffer);$i++)
			$import[$j][$i] = $buffer[$i];
		$j++;
	}

	// Specific field handling.  These are in no particular order, and should be re-arranged and streamlined.

	for($l=1;$l<count($import);$l++) {
		$insert_statement = $insert_statement_starter;
		$requests = 0;
		$notes = "";
		for($k=0;$k<count($import[0]);$k++) {
			//echo $import[0][$k] . " | " . $import[$l][$k];
			switch ($import[0][$k]) {
				case "uid":
				case "order_status":
				case "product_count":
				case "delivery_first_name":
				case "delivery_last_name":
				case "delivery_phone";
				case "delivery_company":
				case "delivery_street1":
				case "delivery_street2":
				case "delivery_city":
				case "delivery_zone":
				case "delivery_postal_code":
				case "delivery_country":
				case "billing_first_name":
				case "billing_last_name":
				case "billing_company":
				case "billing_street2":
				case "billing_zone":
				case "currency":
				case "created":
				case "modified":
				case "host":
				case "order_product_id":
				case "nid":
				case "title":
				case "manufacturer":
				case "model":
				case "qty":
				case "cost":
				case "price":
				case "weight":
				case "attribute-Electronic Signature":
					//echo " | Dropped ";
					break;								// these are fields not used by Dealers
				case "attribute-What items will you be selling?":
					$notes .= "Selling: " . $import[$l][$k] ."\n";
					break;
				case "payment_method":					// payment method filter
					switch ($import[$l][$k]) {			// 0, 3, and 4 are guesses based on my
						case ("none provided"):			// configuration and may need adjustment
							$insert_statement .= "0,";
							break;
						case ("credit"):
							$insert_statement .= "1,";
							break;
						case ("check"):
							$insert_statement .= "2,";
							break;
						case ("money Order"):
							$insert_statement .= "3,";
							break;
						case ("cash"):
							$insert_statement .= "4,";
							break;
						}
					break;
				case "attribute-Are there any dealers you'd like to be next to?":	// Adjacency request
					if ($import[$l][$k] != "") {
						$insert_statement .= "\"1\",";
						$notes .= "Adjacent to: " . $import[$l][$k] . "\n";
						$requests = 1;
					}
					else
						$insert_statement .= "\"0\",";
					break;
				case "attribute-Are there any dealers that you would like to be away from?":
					if ($import[$l][$k] != "") {			// "away from" request
						$insert_statement .= "\"1\",";
						$notes .= "Away from: " . $import[$l][$k] . "\n";
						$requests = 1;
					}
					else
						$insert_statement .= "\"0\",";
					break;
				case "attribute-Would you like to request a specific table? (e.g. B24, A16, E15-16)":
					if ($import[$l][$k] != "") {			// specific assignment request
						$insert_statement .= "\"1\",";
						$notes .= "Specific request: " . $import[$l][$k] . "\n";
						$requests = 1;
					}
					else
						$insert_statement .= "\"0\",";
					break;
				case "order_total":					// for some reason, UltraCart pads to 5 decimals...
					$insert_statement .= "\"" . substr($import[$l][$k], 0, strlen($import[$l][$k])-3) . "\",";
					break;
				case "attribute-Table Size":		// Table Size
					$criteria = substr($import[$l][$k],0,4);
					switch ($criteria) {
						case "Half":
							$table_size = 0;
							break;
						case "Full":
							$table_size = 1;
							break;
						case "Doub":
							$table_size = 2;
							break;
						case "Trip":
							$table_size = 3;
							break;
						case "Isla":
							$table_size = 4;
							break;
						default:
							$table_size = 0;
					}
					if (strpos($import[$l][$k], 'power'))
						$amenity_p = 1;
					else $amenity_p = 0;
					if (strpos($import[$l][$k], 'wall'))
						$amenity_w = 1;
					else $amenity_w = 0;
					$insert_statement .= "\"" . $table_size . "\"," .
										 "\"" . $amenity_p  . "\"," .
										 "\"" . $amenity_w  . "\",";
					break;
				case "delivery_street1":		// our forms only have one Street Address field
					$insert_statement .= "\"" . $import[$l][$k] . " " . $import[$l][$k+1] . "\",";
					break;
				case "billing_state":			// pre-translated 'zones'
					$insert_statement .= "\"" . $import[$l][$k] . "\",";
					break;
				case("attribute-PA Sales Tax Number"):		// tax ID filter, again because of free text fields
					$insert_statement .= "\"" . preg_replace("/[^0-9]/","",str_replace(" ", "",str_replace("-", "", $import[$l][$k]))) . "\",";
					break;
				case("billing_country"):		// country is also encoded
					//die("Entering delivery_country switch; debug exit");
					switch ($import[$l][array_search("delivery_country", $import[0])]) {
						case "840":
							$country = "USA";
							break;
						case "36":
							$country = "Australia";
							break;
						case "124":
							$country = "Canada";
							break;
						case "250":
							$country = "France";
							break;
						case "276":
							$country = "Germany";
							break;
						case "554":
							$country = "New Zealand";
							break;
						default:
							$country = $import[$l][array_search("delivery_country", $import[0])];
							break;
					}
					$insert_statement .= "\"" . $country ."\",";
					break;
				default:		// all other fields
					$insert_statement .= "\"" . addslashes($import[$l][$k]) . "\",";
					break;
				}
			}
			$insert_statement .= $requests . ",0,\"\",0,\"\",0,\"". addslashes($notes) . "\",\"" . date("m/d/Y") . "\");";
			//die($insert_statement);
			echo("<BR>Import of dealer " . $import[$l][array_search("attribute-Name of Dealership",$import[0])]);
			$values[0] = $import[$l][array_search("attribute-Name of Dealership",$import[0])];
			$values[1] = $import[$l][array_search("order_id",$import[0])];
			if (!mysql_query($insert_statement)) {
				echo (" failed: " . mysql_error());
				$values[2] = 0;
			} else {
				$values[2] = 1;										// generates an image for the Layout Report
				$y = 5;
				$im = @imagecreate(300, 50)
				  or die('Cannot Initialize new GD image stream');
				$background_color = imagecolorallocate($im, 102,204,255);
				$text_color = imagecolorallocate($im, 0, 0, 0);
				$line_color = imagecolorallocate($im, 255, 255, 255);
				$dealer = explode("\n", wordwrap($values[0],30,"\n",1));
				foreach ($dealer as $text) {
				//for ($i=0;$i<=sizeof($dealer);$i++) {
					imagestring($im, 4, 40, $y, $text, $text_color);
					$y += 16;
				}
				imageline($im, 0, 0, 300, 0, $line_color);
				$clean_file_name = strtolower(str_replace($to_remove,"",$values[0]));
				$filename = "./images/" .  $clean_file_name . ".png";
				imagepng($im, $filename);
				imagedestroy($im);
				echo (" was successful.");
			}
			RecordLogEntry($values);
		}
	}

	fclose($handle);
	mysql_close($connect)

?></pre>